﻿package idv.etrex.display.object 
{
	import flash.events.Event;
	import idv.etrex.display.XGraphicsExecutor;	
	import idv.etrex.events.PlayerEvent;
	import idv.etrex.display.object.Xhape;
	import idv.etrex.display.XGraphics;

		
		/** 
		 * 動畫撥放完時丟出
		 * @eventType Complete;
		 */
		[Event(name = "Complete", type = "idv.etrex.events.PlayerEvent")]
		
	/**
	 * DynamicStroke可以用來播放XGraphics動畫。
	 * @author etrex
	 * 
	 */	
	public class DynamicStroke extends Xhape implements IPlayer
	{
		/**
		 * 用來控制每個影格要執行幾個Graphics指令
		 */
		public var playingRate:uint = 1;
		private var _isPlaying:Boolean;
		private var xge:XGraphicsExecutor;
		private var _onComplete:Function = function():void{};
		
		/**
		 * 是否正在播放
		 */
		public function get isPlaying():Boolean{
			return _isPlaying;
		}
		
		/**
		 * 在丟出PlayerEvent.COMPLETE事件前會先執行
		 */
		public function set onComplete(value:Function):void {
			_onComplete = value;
		}
		
		/**
		 * 傳入xgraphics建立物件
		 */
		public function DynamicStroke(xg:XGraphics = null) 
		{
			super();
			if(xg != null)
				xgraphics = xg;
			xge = new XGraphicsExecutor(this.flashGraphics, this.xgraphics);
		}
		
		/**
		 * 播放
		 */
		public function play():void {
			_isPlaying = true;
			this.addEventListener(Event.ENTER_FRAME, whenEnterFrame);
		}

		/**
		 * 從頭播放
		 */
		public function replay():void  {
			stop();
			play();
		}
		
		/**
		 * 暫停播放
		 */
		public function pause():void  {
			_isPlaying = false;
			this.removeEventListener(Event.ENTER_FRAME, whenEnterFrame);
		}
		
		/**
		 * 停止播放
		 */
		public function stop():void  {
			this.xge.reset();
			this.graphics.clear();
			pause();
		}
		
		private function whenEnterFrame(e:Event):void {
			for (var i:int = 0 ; i < playingRate ; i++)
			{
				//trace("whenEnterFrame");
				if ( xge.executeOne() == true)
				{
					playComplete();
					break;
				}
			}
		}
		
		private function playComplete():void{
				pause();
				_onComplete.apply(this);
				this.dispatchEvent(new PlayerEvent(PlayerEvent.COMPLETE));
		}
	}
}